/*
 * @description: 
 * @version: 1.0.1
 * @Author: xuqiulin
 * @Date: 2021-06-08 17:19:53
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-06-08 20:12:10
 */

import BackgroundCtrl from "./BackgroundCtrl";
import ShipCtrl from "./ShipCtrl";
import StartCtrl from "./StartCtrl";

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(BackgroundCtrl)
    backgroundCtrl: BackgroundCtrl = null;
    @property(StartCtrl)
    startCtrl: StartCtrl = null;
    @property(cc.AudioSource)
    bgm: cc.AudioSource = null;
    @property(ShipCtrl)
    player: ShipCtrl = null;

    iSpeed: number = 500;
    bBullet: boolean = false;

    @property(cc.Prefab)
    bulletPrefab: cc.Prefab = null;
    iBulletTime: number = 0.1;
    iBulletSum: number = 0;


    onLoad () {
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouch, this);

        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
    }

    start () {

    }

    update (dt: number) {

        if (this.bBullet) {
            this.iBulletSum += dt;
            if (this.iBulletSum > this.iBulletTime) {
                this.iBulletSum = 0;
                // 使用给定的模板在场景中生成一个新节点
                var newBullet = cc.instantiate(this.bulletPrefab);
                // 将新增的节点添加到 Canvas 节点下面
                this.node.addChild(newBullet);
                // 为子弹设置一个随机位置
                newBullet.setPosition(this.player.node.getPosition());
            }
        }
    }

    onTouch () {
        this.backgroundCtrl.startRoll();
        this.startCtrl.close();
    }

    onKeyDown(event){
        switch(event.keyCode){
        case cc.macro.KEY.j:
            this.bBullet = true;
            break;
        }
    }

    onKeyUp(event){
        switch(event.keyCode){
        case cc.macro.KEY.j:
            this.bBullet = false;
            break;
        }
    }
}
